<template>
    <div class="my-calendar" ref="calendar" v-loading="loading">
        <div class="title">
            <div class="year-month">
                <el-button size="mini" @click="prevMonth"><i class="fa fa-chevron-left"></i></el-button>
                <h3>{{year_month}}</h3>
                <el-button size="mini" @click="nextMonth"><i class="fa fa-chevron-right"></i></el-button>
            </div>
        </div>
        <template v-for="(value, key) in day">
            <div class="item">
                <el-button type="text" @click="click(key)" :disabled="value.disabled">{{value.text}}</el-button>
            </div>
        </template>
    </div>
</template>

<script>
    export default {
        name: "calendar",
        props: ['date', 'loading', 'change'],
        data() {
            return {
                now: null,
                year_month: '',
                day: {},
            };
        },
        methods: {
            changeMonth(isEmit) {
                this.year_month = this.now.format('YYYY年MM月');
                const monthEnd = this.now.clone().endOf('month');
                let now = this.now.clone().startOf('month');
                this.day = {};
                const date = this.date ? this.date : [];
                while (now < monthEnd) {
                    const d = now.format('YYYY-MM-DD');
                    this.day[d] = {text: now.get('date'), disabled: date.indexOf(d) === -1};
                    now = now.add(1, 'day');
                }
                now = this.now.format('YYYY-MM');
                if (isEmit) {
                    if (this.change)
                        this.change(now);
                    this.$emit('change', now);
                }
            },
            nextMonth() {
                this.now.add(1, 'month');
                this.changeMonth(true);
            },
            prevMonth() {
                this.now.subtract(1, 'month');
                this.changeMonth(true);
            },
            click(date) {
                this.$emit('click', date);
            },
        },
        watch: {
            date() {
                this.changeMonth(false);
            },
        },
        mounted() {
            this.now = moment();
            this.changeMonth(true);
        },
    }
</script>

<style scoped>


    .my-calendar {
        width: 350px;
        height: auto;
    }

    .my-calendar .title {
        text-align: center;
    }

    .my-calendar .title h3 {
        display: inline-block;
        margin: 0 8px;
    }

    .my-calendar .year-month {
        display: inline-block;
        margin: 10px 0;
    }

    .my-calendar .item {
        display: inline-block;
        width: 50px;
        margin: 5px 0;
        text-align: center;
    }
</style>